package logtest

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/text/gregex"
	"github.com/robertkowalski/graylog-golang"
	"time"
)

var Logtest = new(logtestApi)

type logtestApi struct {
	logger *glog.Logger //实现日志HOOK
	gelf   *gelf.Gelf   //整合graylog
}

func (p *logtestApi) Test1() {
	l1 := g.Log()
	l1.SetStdoutPrint(false)
	l1.SetPath("/tmp/log/gf-app")
	l1.SetFlags(glog.F_TIME_TIME | glog.F_FILE_SHORT)
	l1.Printf("this is a log resta")
	l1.Info("this is Info")
	l1.Debug("this is debug")
	l1.Error("this is err")
	l1.SetFlags(glog.F_TIME_TIME | glog.F_FILE_LONG)
	l1.Warning("this is warning")

	glog.SetPath("/tmp/log/gf-app")
	glog.Skip(1).Line(true).Println("xxxx")
	glog.Cat("test1").Println("ssss")
}
func (p *logtestApi) Test2() {
	glog.SetAsync(true)
	for i := 0; i < 10; i++ {
		glog.Async().Println("async log", i)
	}
	glog.Cat("test2").File("test2").Println("sssss2")
	time.Sleep(time.Second)
}

func (p *logtestApi) Test3() {
	glog.Debug(g.Map{"uid": 100, "name": "john"})
	type User struct {
		Uid  int    `json:"uid"`
		Name string `json:"name"`
	}
	glog.Debug(User{100, "xxx"})
}

func (p *logtestApi) Write(b []byte) (n int, err error) { //重载glog.Logger的Write函数
	s := string(b)
	fmt.Println(s)
	//if gregex.IsMatchString(`\[(PANI|FATAL)\]`,s){
	if gregex.IsMatchString(`PANI|FATA`, s) { //根据特定字眼特殊处理，这里是HOOK部分
		fmt.Println("SERIOUS ISSUE OCCURRED I'd better tell monitor in first time")
		//g.Client().PostContent("127.0.0.1:8080",s)
	}

	p.gelf.Send(b) //这里是对应graylog部分
	return p.logger.Write(b)
}

func (p *logtestApi) Test4() {
	glog.SetWriter(&logtestApi{
		logger: glog.New(),
		gelf: gelf.New(gelf.Config{
			GraylogPort:     80,
			GraylogHostname: "127.0.0.1",
			Connection:      "wan",
			MaxChunkSizeWan: 42,
			MaxChunkSizeLan: 1337,
		}),
	})
	glog.Println("FATAL ERROR")
}
